package com.qlm.service.impl;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsApi;
import com.qlm.entity.User;
import com.qlm.service.UserService;

public class UserServiceImpl implements UserService {

	static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

	public User getUserById(String openId) {
		User user = User.dao.findById(openId);
		return user;
	}
	
	public User getUserInfoFromWXAndSave(String openId,ApiResult apiResult) {
		if (!apiResult.isSucceed()){
			logger.error("从微信获取用户信息失败:"+apiResult);
			return null;
		}
		JSONObject jsonObject = JSON.parseObject(apiResult.getJson());
		String nickname = jsonObject.getString("nickname");
		nickname = filterEmoji(nickname);// 过滤emoji表情特殊字符
		String headimgurl = jsonObject.getString("headimgurl");
		User user = new User();
		user.set(OPENID, openId).set(NICK_NAME, nickname).set(CREATE_TIME, new Date())
				.set(HEAD_PIC, headimgurl).save();
		logger.info("添加用户:"+openId);
		return user;
	}

	public User getUserInfoFromWXAndSave(String code, SnsAccessToken token) {
		String openId = token.getOpenid();
		String accessToken = token.getAccessToken();
		ApiResult apiResult = null;
		try{
			apiResult = SnsApi.getUserInfo(accessToken, openId);
		}catch(Exception e){
			logger.error("从微信获取用户信息失败",e);
			return null;
		}
		if (!apiResult.isSucceed()){
			logger.error("从微信获取用户信息失败:"+apiResult);
			return null;
		}
		JSONObject jsonObject = JSON.parseObject(apiResult.getJson());
		String nickname = jsonObject.getString("nickname");
		nickname = filterEmoji(nickname);// 过滤emoji表情特殊字符
		String headimgurl = jsonObject.getString("headimgurl");
		User user = new User();
		user.set(OPENID, openId).set(NICK_NAME, nickname).set(CREATE_TIME, new Date())
				.set(HEAD_PIC, headimgurl).save();
		logger.info("添加用户:"+openId);
		return user;
	}

	private static String filterEmoji(String source) {
		int len = source.length();
		StringBuilder buf = new StringBuilder(len);
		for (int i = 0; i < len; i++) {
			char codePoint = source.charAt(i);
			if (isNotEmojiCharacter(codePoint)) {
				buf.append(codePoint);
			} else {
				buf.append("~~");
			}
		}
		return buf.toString();
	}

	private static boolean isNotEmojiCharacter(char codePoint) {
		return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) || (codePoint == 0xD)
				|| ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
				|| ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
	}
}
